package org.pointex.service.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pointex.dao.impl.UserDetailsDaoImpl;
import org.pointex.domain.AuthInfo;
import org.pointex.domain.UserBaseInfo;
import org.pointex.domain.UserInfo;
import org.pointex.domain.Users;
import org.pointex.service.ViewConvertUtilService;
import org.pointex.util.StringUtil;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserDetailsServiceImpl  implements UserDetailsService {
	@Resource
	UserDetailsDaoImpl detailsDaoImpl;
	
	@Resource
	ViewConvertUtilService viewConvertUtilService;
	
	protected final Log logger = LogFactory.getLog(getClass());
	protected final MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
	public UserDetailsServiceImpl() {
		new HashMap<>();
	}

	public UserDetails loadUserByUsername(String uid)
			throws UsernameNotFoundException, DataAccessException {
		/*
		 * SecurityContextHolder.getContext() .getAuthentication().getName();
		 */
		
		//根据用户名获取数据库(缓存)中的密码，将它与客户端输入的密码进行匹配，成功即授权,不成功抛出异常
		Hashtable<Object, Object> hashtab=viewConvertUtilService.selectByUserName(uid);
		Users user= new Users(uid, hashtab.get("password")+"",true,true,true,true, AuthorityUtils.NO_AUTHORITIES);		
		if (!user.isEnabled()) {
			logger.debug("Query returned no results for user '" + uid
					+ "'");
			throw new UsernameNotFoundException(messages.getMessage(
					"JdbcDaoImpl.notFound", new Object[] { uid },
					"Username {0} not found"));
		}
		
		//开始授权...
		Set<GrantedAuthority> dbAuthsSet = new HashSet<>();
		dbAuthsSet.addAll(loadUserAuthorities(uid));//添加用户权限
		dbAuthsSet.add(new SimpleGrantedAuthority("ROLE_STATIC"));
		List<GrantedAuthority> dbAuths = new ArrayList<>(dbAuthsSet);
		if (dbAuths.size() == 0) {
			logger.debug("User '" + uid
					+ "' has no authorities and will be treated as 'not found'");

			throw new UsernameNotFoundException(messages.getMessage(
					"JdbcDaoImpl.noAuthority", new Object[] { uid },
					"User {0} has no GrantedAuthority"));
		}
		return createUserDetails(uid, dbAuths);
		// return user;
	}

	protected UserDetails createUserDetails(String username,
			List<GrantedAuthority> combinedAuthorities) {
		Users user2 = new Users(username,
				"%r#3d$%", true,
				true, true, true, combinedAuthorities);
//		user.setId(userFromUserQuery.getId());
//		user.setCompanyId(userFromUserQuery.getCompanyId());
//		user.setLoginStat(userFromUserQuery.getLoginStat());
//		user.setLoginDate(userFromUserQuery.getLoginDate());
//		user.setLoginIP(userFromUserQuery.getLoginIP());
//		user.setSalt(userFromUserQuery.getSalt()); 

		return user2;
	}

	/**
	 * Loads authorities by executing the SQL from
	 * <tt>groupAuthoritiesByUsernameQuery</tt>.
	 *
	 * @return a list of GrantedAuthority objects for the user
	 */

	protected List<GrantedAuthority> loadUserAuthorities(String uid) {
		try {
			Hashtable<Object, Object> hashtable=viewConvertUtilService.authBuUserId(uid);
			
			AuthInfo authInfo = new AuthInfo() ;
			authInfo.setName(hashtable.get("NAME").toString());
			authInfo.setPower_code(hashtable.get("NAME").toString());			
			String roleName = getRolePrefix() + authInfo.getPower_code();
			List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
			SimpleGrantedAuthority s  = new SimpleGrantedAuthority(roleName) ;
			authList.add(s);
			return authList ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getRolePrefix() {
		return "ROLE_";
	}
}